package com.jnc.pay.util.pay;

import cn.hutool.core.util.StrUtil;
import com.jnc.pay.biz.common.model.AlipayConfig;
import com.jnc.pay.biz.common.model.WechatpayConfig;
import com.jnc.pay.biz.common.service.AlipayConfigService;
import com.jnc.pay.biz.common.service.WechatpayConfigService;
import com.jnc.pay.constant.RedisConstant;
import com.jnc.pay.core.config.redis.RedisStore;
import com.jnc.pay.util.convert.ConvertUtil;
import com.jnc.pay.util.convert.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Auther: jjn
 * @Date: 2020/6/28 14:15
 * @Desc: 微信支付工具类
 */
@Component
public class WechatPayUtil {

    @Autowired
    private RedisStore redisStore;
    @Autowired
    private WechatpayConfigService wechatpayConfigService;
    @Autowired
    private AlipayConfigService alipayConfigService;

    //获取微信支付配置
    public WechatpayConfig getWechatpayConfig(String appId){
        String json = ConvertUtil.toStr(redisStore.get(RedisConstant.WECHATPAY_CONFIG + appId));
        //缓存取不到，数据库里取
        if(StrUtil.isBlank(json)){
            WechatpayConfig wechatpayAppConfig = wechatpayConfigService.getWechatpayAppConfig(appId);
            if(wechatpayAppConfig != null){
                //先清空老的缓存数据
                redisStore.del(RedisConstant.WECHATPAY_CONFIG + appId);
                //再存入新的缓存数据
                redisStore.set(RedisConstant.WECHATPAY_CONFIG + appId, JsonUtil.bean2Json(wechatpayAppConfig));
            }
            return wechatpayAppConfig;
        }
        return JsonUtil.json2Bean(json, WechatpayConfig.class);
    }

    /**
     * 获取支付宝支付配置
     * @param appId
     * @return
     */
    public AlipayConfig getAlipayConfig(String appId){
        String json = ConvertUtil.toStr(redisStore.get(RedisConstant.ALIPAY_CONFIG + appId));
        //缓存取不到，数据库里取
        if(StrUtil.isBlank(json)){
            AlipayConfig alipayAppConfig = alipayConfigService.getAlipayAppConfig(appId);
            if(alipayAppConfig != null){
                //先清空老的缓存数据
                redisStore.del(RedisConstant.ALIPAY_CONFIG + appId);
                //再存入新的缓存数据
                redisStore.set(RedisConstant.ALIPAY_CONFIG + appId, JsonUtil.bean2Json(alipayAppConfig));
            }
            return alipayAppConfig;
        }
        return JsonUtil.json2Bean(json, AlipayConfig.class);
    }
}
